<template>
  <div class="upload-test">
    <h2>图片上传测试</h2>
    
    <!-- 上传测试 -->
    <div class="test-section">
      <h3>测试图片上传</h3>
      <el-upload
        class="upload-demo"
        action="#"
        :show-file-list="false"
        :before-upload="beforeUpload"
        :http-request="handleUpload"
      >
        <el-button type="primary">选择图片</el-button>
      </el-upload>
    </div>

    <!-- 上传结果 -->
    <div class="result-section" v-if="uploadResult">
      <h3>上传结果</h3>
      <div class="result-item">
        <strong>文件路径:</strong> {{ uploadResult.filePath }}
      </div>
      <div class="result-item">
        <strong>文件名:</strong> {{ uploadResult.fileName }}
      </div>
      <div class="result-item">
        <strong>文件大小:</strong> {{ uploadResult.fileSize }} bytes
      </div>
      <div class="result-item">
        <strong>上传状态:</strong> 
        <span :class="uploadResult.success ? 'success' : 'error'">
          {{ uploadResult.success ? '成功' : '失败' }}
        </span>
      </div>
      <div class="result-item" v-if="uploadResult.errorMessage">
        <strong>错误信息:</strong> {{ uploadResult.errorMessage }}
      </div>
    </div>

    <!-- 图片预览 -->
    <div class="preview-section" v-if="uploadResult && uploadResult.success">
      <h3>图片预览</h3>
      <div class="preview-item">
        <h4>使用后端返回的路径:</h4>
        <img 
          :src="getImageUrl(uploadResult.filePath)" 
          class="preview-image"
          @load="handleImageLoad"
          @error="handleImageError"
          alt="预览图片"
        />
        <div class="image-status" :class="imageStatus">
          {{ imageStatus === 'loading' ? '加载中...' : 
             imageStatus === 'success' ? '加载成功' : 
             imageStatus === 'error' ? '加载失败' : '未测试' }}
        </div>
      </div>
    </div>

    <!-- 调试信息 -->
    <div class="debug-section">
      <h3>调试信息</h3>
      <el-button @click="showDebugInfo" type="info">显示调试信息</el-button>
      <div v-if="debugInfo" class="debug-content">
        <pre>{{ JSON.stringify(debugInfo, null, 2) }}</pre>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { uploadOutboundThumbnail } from '@/api/outboundOrder'

// 配置后端服务器地址（用于图片访问）
const BACKEND_SERVER_URL = 'http://localhost:5265'

const uploadResult = ref<any>(null)
const imageStatus = ref('loading')
const debugInfo = ref<any>(null)

// 获取图片URL
const getImageUrl = (url: string): string => {
  if (!url) return ''
  
  // 如果是完整URL，直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  
  // 如果是后端返回的文件路径，使用后端服务器地址
  if (url.includes('uploads/')) {
    return `${BACKEND_SERVER_URL}/uploads/${url.replace(/^uploads\//, '')}`
  }
  
  // 其他情况，尝试作为相对路径处理
  return url
}

// 上传前验证
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理上传
const handleUpload = async (options: any) => {
  try {
    const file = options.file
    console.log('开始上传文件:', file.name, file.size, file.type)
    
    const response = await uploadOutboundThumbnail(file)
    console.log('上传响应:', response)
    
    if (response.code === 200 && response.data.success) {
      uploadResult.value = response.data
      imageStatus.value = 'loading'
      ElMessage.success('上传成功')
      
      // 记录调试信息
      debugInfo.value = {
        originalFile: {
          name: file.name,
          size: file.size,
          type: file.type
        },
        uploadResponse: response,
        filePath: response.data.filePath,
        constructedUrl: getImageUrl(response.data.filePath)
      }
    } else {
      uploadResult.value = {
        success: false,
        errorMessage: response.msg || '上传失败'
      }
      ElMessage.error(response.msg || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    uploadResult.value = {
      success: false,
      errorMessage: error instanceof Error ? error.message : '上传失败'
    }
    ElMessage.error('上传失败')
  }
}

// 处理图片加载成功
const handleImageLoad = () => {
  imageStatus.value = 'success'
  console.log('图片加载成功')
}

// 处理图片加载失败
const handleImageError = () => {
  imageStatus.value = 'error'
  console.log('图片加载失败')
}

// 显示调试信息
const showDebugInfo = () => {
  debugInfo.value = {
    backendServerUrl: BACKEND_SERVER_URL,
    windowLocationOrigin: window.location.origin,
    uploadResult: uploadResult.value,
    constructedUrl: uploadResult.value ? getImageUrl(uploadResult.value.filePath) : null
  }
}
</script>

<style scoped>
.upload-test {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.test-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f5f5f5;
  border-radius: 8px;
}

.result-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 8px;
}

.result-item {
  margin-bottom: 10px;
  line-height: 1.6;
}

.result-item .success {
  color: #52c41a;
  font-weight: bold;
}

.result-item .error {
  color: #ff4d4f;
  font-weight: bold;
}

.preview-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 8px;
}

.preview-item {
  text-align: center;
}

.preview-image {
  max-width: 300px;
  max-height: 200px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  margin: 10px 0;
}

.image-status {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  display: inline-block;
  margin-top: 10px;
}

.image-status.loading {
  background: #e6f7ff;
  color: #1890ff;
}

.image-status.success {
  background: #f6ffed;
  color: #52c41a;
}

.image-status.error {
  background: #fff2f0;
  color: #ff4d4f;
}

.debug-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.debug-content {
  margin-top: 15px;
  padding: 15px;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  overflow-x: auto;
}

.debug-content pre {
  margin: 0;
  font-size: 12px;
  line-height: 1.4;
}
</style>



